<template>
	<div class="tikuBg">
		<div class="limitBox" v-if="!limitStatus">
			<div class="formBox" v-if="!nolimit">
				<h3>面试题库登录</h3>
				<p>雪恒教育-白雪面试内部专用</p>
				<div class="btn"><u-button type="error" text="点击登录" @click="toLogin()"></u-button></div>
			</div>
			<div class="formBox" v-else>
				<h3>您暂无权限，请联系教务老师给您添加权限</h3>
			</div>
		</div>
		
		<u-popup :show="showBj" mode="center" :safeAreaInsetBottom="false">
			<div class="popContent">
				<div class="overBox">
					<ul class="squre_bj">
						<li v-for="(bj,index) in userinfo" :key="index" @click="changeBj(bj.banji)">
							<h3>{{ bj.banji }}</h3>
						</li>
					</ul>
				</div>
				
			</div>
		</u-popup>
		
		<u-popup :show="showMoshi" mode="center" :safeAreaInsetBottom="false">
			<div class="popContent" v-if="banjiDetail">
				<div class="overBox">
					<ul class="squre_moshi half">
						<li v-for="(item,index) in moshiList" :key="index" @click="changeMoshi(item,index)" class="textCenter">
							<h3>{{ item.name }}</h3>
						</li>
						<li class="textCenter back_btn" @click="showMoshi = false; showBj = true">上一步</li>
					</ul>
				</div>
				
			</div>
		</u-popup>
		
		
		<u-popup :show="showZuti" mode="center" :safeAreaInsetBottom="false">
			<div class="popContent" v-if="banjiDetail">
				<div class="overBox">
					<ul class="squre_moshi">
						<li v-for="(item,index) in taotiList" :key="index" @click="changeTaoti(item)">
							<h3>{{ item.title }}</h3>
							<p>{{ item.intro }}</p>
						</li>
						
					</ul>
					<ul class="squre_moshi half">
						<li class="textCenter" @click="showNewTi = true;showZuti=false">
							<h3>添加套题+</h3>
						</li>
						<li class="textCenter back_btn" @click="showZuti = false; showMoshi = true">上一步</li>
					</ul>
				</div>
				
			</div>
		</u-popup>
		
		<u-popup :show="showNewTi" mode="center" :safeAreaInsetBottom="false">
			<div class="popContent">
				<u--input placeholder="日期+模式" border="surround" v-model="newTaoti"></u--input>
				<u-gap height="10" bgColor="#fff"></u-gap>
				<u--input placeholder="时间+题量" border="surround" v-model="newTaotiIntro"></u--input>
				<u-gap height="20" bgColor="#fff"></u-gap>
				
				<div class="btns">
					<div class="btn"><u-button type="error" :plain="true" text="取消" @click="showNewTi = false;showZuti=true"></u-button></div>
					<div class="btn"><u-button type="error" text="提交" @click="addTaotiname()"></u-button></div>
				</div>
				
			</div>
		</u-popup>
		
		
		<u-popup :show="welcome" mode="center" :safeAreaInsetBottom="false">
			<div class="popText">
				<u-loading-icon size="36" mode="circle" :vertical="true" color="red" text="推送中..." textSize="20"></u-loading-icon>
			</div>
		</u-popup>
		<u-sticky bgColor="#fff">
			<div class="banner">
				<image src="https://www.baixuemianshi.com/zhuanti/images/swiper_xcx2.jpg" mode="widthFix"></image>
			</div>
			<u-tabs :list="lxList"  :current="yjCurrent" @change="changeTabs"></u-tabs>
			<div v-if="ejlxList.length > 0" class="subFilter">
				<u-tabs :list="ejlxList" :current="ejCurrent" @change="changeEjTabs" lineColor="#f56c6c"></u-tabs>
			</div>
			
			<div class="searchBox">
				<u-search placeholder="输入关键字搜索" shape="round" v-model="searchVal"></u-search>
			</div>
			
			<div class="userInfo"> {{ userinfo[0].teacher }}老师，当前班级：{{ selectBj }}</div>
		</u-sticky>
		
		<div class="container">
			
			<div class="loadBox" v-if="searchLoading">
				<u-loading-icon size="36" mode="circle" :vertical="true" color="red" text="加载中..." textSize="20"></u-loading-icon>
			</div>
			<div class="items" v-else>
				<div class="item" v-for="(item,index) in searchList" :key="index">
					<h3 v-html="addGl(item.title)"></h3>
					<ul class="tags">
						<u-tag :text="item.leixing" plain size="mini" type="warning"></u-tag>
					</ul>

					<div class="btns">
						<div class="btn" v-if="item.answerDetail">
							<u-button type="error" size="mini" text="查看逐字稿" @click="showAnswer(item)"></u-button>
						</div>
						<div class="btn" v-if="checkFav(item)">
							<u-button type="primary" size="mini" text="添加+" @click="addFav(item)"></u-button>
						</div>
						<div class="btn" v-else>
							<u-button type="primary" plain size="mini" text="取消+" @click="removeFav(item)"></u-button>
						</div>
					</div>
				</div>
			</div>
		</div>

		<div class="detailBtn" v-if="selectMoshi">
			<div>
				<u-button type="success"  size="small" text="更改班级" @click="showBj = true"></u-button>
			</div>
			<div v-if="selectMoshi.spell == 'zuti'">
				<u-button type="warning"  size="small" text="更改套题" @click="showZuti = true"></u-button>
			</div>
			<div>
				<u-button type="primary"  size="small" text="已选题目" @click="showDetail = true"></u-button>
			</div>
			<div>
				<u-button type="error"  size="small" text="分享题目" open-type="share"></u-button>
			</div>
		</div>

		<div class="detailBox" v-if="showDetail">
			<div class="content">
				<div class="close" @click="showDetail = false"><u-icon name="close-circle" size="28"
						color="#000"></u-icon></div>
				<div v-if="selectMoshi.spell == 'zuti'">
					<u-divider :text="selectTaoti.title" textPosition="left" textSize="18" textColor="#d9232f" lineColor="#d9232f"></u-divider>
					<div class="intro">{{selectTaoti.intro}}</div>
				</div>
				
				
				<div class="item" v-for="(item,index) in favList" :key="index">
					<h3>{{index + 1}}、[{{ item.leixing }}] {{ item.title }}</h3>
					<div class="d_btns">
						<div class="btn"><u-button type="error" size="mini" text="删除" @click="removeFav(item)"></u-button></div>
						<div class="btn">
							<div v-if="!checkAnswer(item)">
								<u-button type="success" size="mini" text="显示逐字稿" @click="changeAnswer(item)"></u-button>
							</div>
							<div v-else>
								<u-button type="success" size="mini" plain text="隐藏逐字稿" @click="changeAnswer(item)"></u-button>
							</div>
						</div>
						<div class="time">{{item.time}}</div>
					</div>
					
				</div>
			</div>
		</div>
		<canvas canvas-id="waterMark" class="waterMark" style="width: 100vw; height: 100vh;"></canvas>
		<image :src="waterMarkUrl" class="waterMark-bg" style="width: 100vw; height: 100vh;"></image>
	</div>
</template>

<script>
	import {
		mapActions
	} from 'vuex';
	const db = wx.cloud.database()
	export default {
		data() {
			return {
				waterMarkUrl: "",
				windowWidth: 100,
				windowHeight: 100,
				userinfo: {},
				showBj: false,
				selectBj: "",
				showMoshi: false,
				selectMoshi: {name: "组题模式",spell: "zuti"},
				selectMoshiIndex: 0,
				moshiList: [
					{name: "组题模式",spell: "zuti"},
					{name: "作业模式",spell: "homework"},
				],
				showZuti: false,
				taotiList:[],
				showNewTi:false,
				selectTaoti:"",
				taotiIntro:"",
				newTaoti:"",
				newTaotiIntro:"",
				nowSelectList:[],
				
				
				
				nolimit: false,
				welcome: false,
				leixings: [],
				lxList: [],
				lists: [],
				yjCurrent: 1,
				filterLxName: "全部类型",
				ejlxList: [],
				filterErlx: "",
				ejCurrent: 1,

				banjiDetail: {
					name: '',
					phone: '',
					banji: '',
					zuti: [],
					homework: []
				},
				searchLoading:true,

				addIdList: [],
				showDetail: false,
				time: "",
				
				limitStatus:false,
				searchVal: "",
				pages: 0
			}
		},
		onShareAppMessage(res) {
			if (res.from === 'button') { // 来自页面内分享按钮
				return {
					title: `题库-学员端`, //分享标题
					path: '/pages/nbhd/tiku/student', //分享页面路径
					imageUrl: '', //分享图标
					desc: '雪恒教育-白雪面试', //自定义分享描述 
				}
			} else {
				return {
					title: `题库-学员端`, //分享标题
					path: '/pages/nbhd/tiku/student', //分享页面路径
					imageUrl: '', //分享图标
					desc: '雪恒教育-白雪面试', //自定义分享描述 
				}
			}
		},
		onLoad(options) {
			
		},
		onShow() {
			if(wx.setVisualEffectOnCapture){
			    wx.setVisualEffectOnCapture({
			        visualEffect: 'hidden',
			        success:(res) => {
			            console.log('success回调',res)
			        },
			    })
			}
		},
		onHide() {
			if(wx.setVisualEffectOnCapture){
			    wx.setVisualEffectOnCapture({
			        visualEffect: 'none',
			        success:(res) => {
			            console.log('success回调',res)
			        },
			    })
			}
		},
		computed: {
			userphone() {
				return this.$store.getters.userphone ? this.$store.getters.userphone : '';
			},
			favList() {
				let that = this
				let fList = []
				if(that.selectMoshi.spell == 'zuti'){
					fList = that.banjiDetail[that.selectMoshi.spell].filter(item => item.taotiname == that.selectTaoti.title)
				}else{
					fList = that.banjiDetail[that.selectMoshi.spell]
				}
				return fList
			},
			removeSelect(){
				let that = this
				let l = []
				let myArray = that.banjiDetail[that.selectMoshi.spell]
				myArray = myArray.filter(item => item.taotiname != that.selectTaoti.title);
				let arr = that.lists
				myArray.map(removeItem => {
					arr = arr.filter(item => item._id != removeItem._id)
				})
				return arr 
			},
			searchList(){
				let that = this
				
				let l = []
				if(that.searchVal){
					l = that.removeSelect.filter(item => item.title.indexOf(that.searchVal) != -1)
				}else{
					l = that.removeSelect
				}
				return l
			}
		},
		created() {
			let that = this;
			let date = new Date()
			let year = date.getFullYear()
			let month = date.getMonth() + 1
			let day = date.getDate()
			that.time = year + '/' + month + '/' + day
			that.getLeixing()
		},
		mounted() {
			let that = this 
			if(that.userphone){
				that.getuserStatus()
			}
			wx.hideLoading()
			
			if(this.userphone){
				this.drawWaterMark(this.userphone);
			}else{
				this.drawWaterMark('雪恒教育-白雪面试');
			}
		},
		watch: {
			userphone(val){
				if (this.userphone) {
					this.getuserStatus()
				}
			}
		},
		methods: {
			...mapActions(['LogSetPhone']),
			drawWaterMark(text) {
				this.getDeviceInfo().then(response => {
					const w = response.windowWidth;
					const h = response.windowHeight;
					this.windowWidth = w;
					this.windowHeight = h;
					//创建canvas绘制上下文
					const canvas = uni.createCanvasContext("waterMark", this);
					canvas.clearRect(0, 0, w, h)
					//开始创建一个路径，需要调用fill或者stroke才会使用路径进行填充或描边。
					canvas.beginPath();
					canvas.setFontSize(18);
					canvas.setFillStyle('rgba(0, 0, 0, 0.1)');
					canvas.rotate(-30 * Math.PI / 180)
					if (text) {
						text = this.trim(text)
					}
					const maxWidth = text.length * 18
					for (let x = 0; x < 10; x++) {
						for (let y = 0; y < 20; y++) {
							//在画布上绘制被填充的文本。
							canvas.fillText(text, (maxWidth + 40) * x - 400, 90 * y + 20);
						}
					}
					//将之前在绘图上下文中的描述（路径、变形、样式）画到 canvas 中。
					canvas.draw(false, () => {
						//把当前画布指定区域的内容导出生成指定大小的图片
						uni.canvasToTempFilePath({
							canvasId: "waterMark",
							complete: (res) => {
								this.waterMarkUrl = res.tempFilePath
							}
						}, this)
					})
				});
			},
			trim(str) {
				let trimStr = '';
				const reg = /[\t\r\f\n\s]*/g;
				if (typeof str === 'string') {
					trimStr = str.replace(reg, '');
				}
				return trimStr
			},
			/**
			 * 获取当前设备的信息
			 * **/
			getDeviceInfo() {
				return new Promise((resolve, reject) => {
					uni.getSystemInfo({
						success: (sysInfo) => {
							resolve(sysInfo)
						}
					})
				})
			},
			toLogin(){
				uni.navigateTo({
					url: '../../my/login'
				})
			},
			async getuserStatus(){
				let that = this
				
				db.collection('nbhd_tiku_banjilist').where({
					phone: that.userphone
				}).get({
					success: function(res){
						if(res.data.length > 0){
							that.userinfo = res.data
							that.showBj = true
							uni.showToast({
								title: '登录成功',
								icon: 'success'
							})
							
							that.limitStatus = true
						}else{
							uni.showToast({
								title: '暂无权限',
								icon: 'error'
							})
							that.nolimit = true
						}
					},
					fail: function(req){
						uni.showToast({
							title: '暂无权限',
							icon: 'error'
						})
					}
				})
			},
			getLeixing(){
				let that = this
				db.collection('nbhd_chanyan_lxs').doc("0b153f9a6594b720058c8bec1e411fd5").get().then(res => {
					that.leixings = res.data.lxList
					that.filterLx()
				})
			},
			getList() {
				let that = this
				db.collection('nbhd_chanyan').where({
					type: that.filterLxName,
					leixing: that.filterErlx
				}).skip(that.pages * 20).limit(20).get({
					success: res =>{
						if(res.data.length > 0){
							that.lists = that.lists.concat(res.data)
							that.pages += 1
							that.getList()
						}
						that.searchLoading = false
					}
				})
			},
			filterLx() {
				let that = this
				let lxs = that.leixings.map(item => item.type)
				// lxs.unshift('全部类型')
				let lxNames = []
				lxs.map(item => {
					lxNames.push({
						"name": item
					})
				})
				that.lxList = lxNames
				that.yjCurrent = 0
				that.filterLxName = lxs[0]
				that.filterEjLx()
			},
			filterEjLx() {
				let that = this
				let ejList = that.leixings[that.yjCurrent].lxs
				let ejlxNames = []
				ejList.map(item => {
					ejlxNames.push({
						"name": item.title
					})
				})
				that.ejlxList = ejlxNames.length > 1 ? ejlxNames : []
				that.ejCurrent = 0
				if (ejlxNames.length > 1) {

					that.filterErlx = that.ejlxList[0].name
				} else {
					that.filterErlx = ''
				}
				that.getList()
				
				wx.hideLoading()
			},
			changeTabs(e) {
				this.searchVal = ''
				this.yjCurrent = e.index
				this.filterLxName = e.name
				this.searchLoading = true
				this.lists = []
				this.pages = 0
				this.filterEjLx()
			},
			changeEjTabs(e) {
				this.searchVal = ''
				this.ejCurrent = e.index
				this.filterErlx = e.name
				this.searchLoading = true
				this.lists = []
				this.pages = 0
				this.getList()
			},
			checkFav(item) {
				let that = this
				let idList = that.banjiDetail[that.selectMoshi.spell].filter(l => l.taotiname == that.selectTaoti.title)
				let iList = idList.map(info => info._id)
				let c = iList.includes(item._id)
				return !c
			},
			addFav(item) {
				let that = this
				if(that.selectMoshi.spell == "zuti"){
					that.banjiDetail[that.selectMoshi.spell].push({taotiname:that.selectTaoti.title,taotiIntro:that.selectTaoti.intro,_id: item._id,leixing: item.leixing,title: item.title,answer: false,time:  that.getTime() })
				}else if(that.selectMoshi.spell == "homework"){
					that.banjiDetail[that.selectMoshi.spell].push({_id: item._id,leixing: item.leixing,title: item.title,answer: true,time:  that.getTime() })
				}
				
				that.saveUserInfo()
			},
			removeFav(obj) {
				let that = this
				let myArray = that.banjiDetail[that.selectMoshi.spell]
				myArray = myArray.filter(item => item._id != obj._id);
				that.banjiDetail[that.selectMoshi.spell] = myArray
				that.saveUserInfo()
				
			},
			pushContent() {
				let that = this
				that.welcome = true
				that.saveUserInfo()
			},
			getTimuInfo(){
				let that = this
				db.collection('nbhd_tiku_banji').where({
					banji: that.selectBj
				}).get({
					success: function(res) {
						if(res.data.length > 0){
							that.banjiDetail = res.data[0]
						}else{
							that.pushEmpty()
						}
						
					}
				})
			},
			pushEmpty(){
				let that = this
				db.collection('nbhd_tiku_banji').add({
					data: {
						teacher: that.userinfo[0].teacher,
						phone: that.userinfo[0].phone,
						banji: that.selectBj,
						time: new Date(),
						timuList:[]
					},
					success: function(res) {
						that.getTimuInfo()
					}
				})
			},
			saveUserInfo(){
				let that = this
				db.collection('nbhd_tiku_banji').doc(that.banjiDetail._id).update({
					data: {
						time: new Date(),
						zuti: that.banjiDetail.zuti,
						homework: that.banjiDetail.homework
					},
					success: function(res) {
						that.welcome = false
					}
				})
			},
			addGl(title){
				let that = this
				if(!that.searchVal){
					return title
				}
				let sText = title
				let sKey = "<span class='searchBg'>" + that.searchVal + "</span>"
				let num = -1,
					rStr = new RegExp(that.searchVal, "g"),
					rHtml = new RegExp("\<.*?\>", "ig"), //匹配html元素
					aHtml = sText.match(rHtml); //存放html元素的数组
				sText = sText.replace(rHtml, '{~}'); //替换html标签
				sText = sText.replace(rStr, sKey); //替换key
				sText = sText.replace(/{~}/g, function() { num++;return aHtml[num];});
				return sText
			},
			changeBj(bj){
				this.selectBj = bj
				this.getTimuInfo()
				this.showBj = false
				this.showMoshi = true
			},
			changeMoshi(moshi,index){
				this.selectMoshi = moshi
				this.selectMoshiIndex = index
				this.showMoshi = false
				if(moshi.spell == 'zuti'){
					let list = []
					let arr = this.banjiDetail.zuti.map(item => item.taotiname)
					arr = [...new Set(arr)]
					arr.map((item,index) =>{
						let f = this.banjiDetail.zuti.filter(n => n.taotiname == item)
						list.push({
							title:item,
							intro:f[0].taotiIntro
						})
					})
					this.taotiList = list
					this.showZuti = true
				}
			},
			addTaotiname(){
				let that = this
				this.taotiList.push({
					title:that.newTaoti,
					intro:that.newTaotiIntro
				})
				this.showZuti = true
				this.showNewTi = false
			},
			changeTaoti(info){
				this.selectTaoti = info
				this.showZuti = false
				
				this.nowSelectList = this.banjiDetail.zuti.filter(item => item.taotiname)
			},
			changePicker(e){
				this.selectMoshiIndex = e.detail.value
				this.selectMoshi = this.moshiList[e.detail.value]
			},
			getTime(){
				let that = this
				let day = new Date()
				let y = day.getFullYear()
				let m = (day.getMonth() + 1).toString().padStart(2, '0');
				let d = day.getDate().toString().padStart(2, '0');
				let hour = day.getHours().toString().padStart(2, '0');
				let miu = day.getMinutes().toString().padStart(2, '0');
				let time = y + '-' + m + '-' + d + ' ' + hour + ':' + miu
				return time
			},
			showAnswer(item){
				let that = this
				uni.navigateTo({
					url:"./answer?tmid=" + item._id
				})
			},
			checkAnswer(info){
				let that = this
				let t = that.banjiDetail[that.selectMoshi.spell].filter((item,index) => item._id == info._id)
				return t[0].answer
			},
			changeAnswer(info){
				let that = this
				let list = that.banjiDetail[that.selectMoshi.spell]
				list.map((item,index) => {
					if(item._id == info._id){
						list[index].answer = !list[index].answer
					}
				})
				that.banjiDetail[that.selectMoshi.spell] = list
				
				that.saveUserInfo()
			},
		},
		components: {
			
		}
	};
</script>

<style>
	@import url(./index.css);
</style>